package com.weixing.mall.provider.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.service.AgentServiceRpc;
import com.weixing.mall.provider.mapper.MediaAdvertsingMapper;
import com.weixing.mall.provider.mapper.MediaAgentBindMapper;
import com.weixing.mall.provider.mapper.MediaOrderdRecordMapper;
import com.weixing.mall.provider.mapper.RoleMapper;
import com.weixing.mall.provider.model.domain.*;
import com.weixing.mall.provider.model.dto.ads.MediaAdvertsingDto;
import com.weixing.mall.provider.model.enums.WhetherEnum;
import com.weixing.mall.provider.model.enums.ads.AdvertsingEunm;
import com.weixing.mall.provider.model.enums.ads.OpenTypeEunm;
import com.weixing.mall.provider.model.enums.sys.SysFlag;
import com.weixing.mall.provider.model.query.FrontMediaAdvertSingQuery;
import com.weixing.mall.provider.model.query.MediaAdvertsingQuery;
import com.weixing.mall.provider.model.vo.FrontMediaAdvertsingDetilVo;
import com.weixing.mall.provider.model.vo.FrontMediaAdvertsingVo;
import com.weixing.mall.provider.model.vo.ads.MediaAdvertsingVo;
import com.weixing.mall.provider.service.IMediaAdvertsingService;
import com.weixing.mall.provider.service.IMediaPlatformService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 广告模块-媒体广告表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-18
 */
@Service
public class MediaAdvertsingServiceImpl extends ServiceImpl<MediaAdvertsingMapper, MediaAdvertsing> implements IMediaAdvertsingService {

    @Autowired
    private MediaOrderdRecordMapper mediaOrderdRecordMapper;
    @Autowired
    private RoleMapper sysRoleMapper;
    @Autowired
    private MediaAgentBindMapper mediaAgentBindMapper;

    @Autowired
    private AgentServiceRpc agentServiceRpc;

    @Autowired
    private MediaOrderdRecordServiceImpl mediaOrderdRecordService;

    @Autowired
    private IMediaPlatformService mediaPlatformService;

    @Override
    public IPage<MediaAdvertsingVo> selectOfPage(Page initMpPage, MediaAdvertsingQuery mediaAdvertsingQuery, Long uid) {


        List<Role> roleList = sysRoleMapper.selectSysRoleByUserId(uid, SysFlag.SYS.getValue());
        int qs = 0;
        ArrayList<Integer> numList = new ArrayList<Integer>();
        for (int i = 0; i < roleList.size(); i++) {
            //角色code是director（广告专员），就只能查自己的
            if (GlobalConstant.RoleCode.DIRECTOR.equals(roleList.get(i).getRoleCode())) {
                qs = 1;
            } else if (GlobalConstant.RoleCode.KF.equals(roleList.get(i).getRoleCode())) {//角色code是customer（广告客服），查客服所属的
                qs = 2;
            } else {//否则查全部的
                qs = 3;
            }
            numList.add(qs);
        }
        //取出最大值
        int type = Collections.max(numList);
        if (type == 1) {//广告专员
            mediaAdvertsingQuery.setDirector(uid);
        } else if (type == 2) {//广告客服
            mediaAdvertsingQuery.setDirector(null);
            mediaAdvertsingQuery.setCustomerId(uid);
        } else {//全部，自由操控

        }


        IPage<MediaAdvertsingVo> pageList = baseMapper.selectOfPage(initMpPage, mediaAdvertsingQuery);
        if (pageList.getRecords() != null && pageList.getRecords().size() > 0) {
            for (MediaAdvertsingVo mav : pageList.getRecords()) {
                int orderNum = mediaOrderdRecordMapper.selectOrderNum(mav.getId());
                mav.setOrderNum(orderNum);
                if(mav.getBusinessId() != null){
                    MediaOrderdRecord mor = mediaOrderdRecordService.getById(mav.getBusinessId());
                    Integer recordStatus = ObjectUtil.isNotEmpty(mor)?mor.getStatus():null;
                    mav.setOrderdStatus(recordStatus);
                }
            }
        }
        return pageList;
    }

    @Override
    public List<MediaAdvertsingVo> getList(MediaAdvertsingQuery mediaAdvertsingQuery) {
        return baseMapper.selectOfPage(mediaAdvertsingQuery);
    }

    @Override
    public List<MediaAdvertsingVo> selectList(MediaAdvertsingQuery mediaAdvertsingQuery) {
        SysAuth sysAuth = AuthUtil.getSysExt();
        if(ObjectUtil.isNotEmpty(sysAuth)){//角色条件判断 这块属于规定若有变动需要更改代码判断
            String ur = sysAuth.getUr();
            //字符串
            String dk = GlobalConstant.RoleCode.DIRECTOR +","+ GlobalConstant.RoleCode.KF;
            if(ur.length() <= dk.length()){//角色字符串长度大于客服和广告专员字符串长度则查询所有的 否则 判断一下是否包含广告专员或者客服角色
                if(ur.contains(GlobalConstant.RoleCode.DIRECTOR)){
                    mediaAdvertsingQuery.setDirector(sysAuth.getUid());
                }
                if(ur.contains(GlobalConstant.RoleCode.KF)){
                    mediaAdvertsingQuery.setDirector(null);
                    mediaAdvertsingQuery.setCustomerId(sysAuth.getUid());
                }
            }
        }
        return baseMapper.selectOfPage(mediaAdvertsingQuery);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(MediaAdvertsingDto mediaAdvertsingDto) {
        MediaAdvertsing mediaAdvertsing = new MediaAdvertsing();
        if(mediaAdvertsingDto.getLaunchDate().length()<11){//二期项目业务调整投放日期为YYYY-MM-DD，则为了系统融合使用，补充 时分秒为00:00:00
            mediaAdvertsingDto.setLaunchDate(mediaAdvertsingDto.getLaunchDate().trim()+" 00:00:00");
        }
        BeanUtils.copyProperties(mediaAdvertsingDto, mediaAdvertsing);
        if (mediaAdvertsingDto.getIsAgentPay() != null) {
            mediaAdvertsing.setIsAgentPay(mediaAdvertsingDto.getIsAgentPay().getValue());
        }
        if (mediaAdvertsingDto.getIsCompanyPay() != null) {
            mediaAdvertsing.setIsCompanyPay(mediaAdvertsingDto.getIsCompanyPay().getValue());
        }
        if (mediaAdvertsingDto.getStaus() != null) {
            mediaAdvertsing.setStaus(mediaAdvertsingDto.getStaus().getValue());
        }
        if (mediaAdvertsingDto.getAdsType() != null) {
            mediaAdvertsing.setAdsType(mediaAdvertsingDto.getAdsType().getValue());
        }
        if (mediaAdvertsingDto.getOpenType() != null) {
            mediaAdvertsing.setOpenType(mediaAdvertsingDto.getOpenType().getValue());
            if (mediaAdvertsingDto.getOpenType().getValue().equals(OpenTypeEunm.TYPE2.getValue())) {//如果为专属开放，则需要存储那个代理商可以查看
                //新增调整逻辑 绑定的代理商agentIds需要前端选择后传递过来 这里若前端传过来为空则默认去查询绑定代理商ID
                List<Long> agentIds = null;
                if(mediaAdvertsingDto.getAgentIds() != null && mediaAdvertsingDto.getAgentIds().size() > 0){
                    agentIds = mediaAdvertsingDto.getAgentIds();
                }else {
                    List<MediaAgentBind> list = mediaAgentBindMapper.selectList(new QueryWrapper<MediaAgentBind>().eq("director", mediaAdvertsingDto.getDirector()));
                    agentIds = list.stream().map(MediaAgentBind::getAgent).collect(Collectors.toList());
                }
               List<Long> tt= Lists.newArrayList();
               for(Long ids:agentIds){
                   Long[]  agentdIds=   agentServiceRpc.selectAgentTreeByParentId(ids);
                   List<Long> tmp = java.util.Arrays.asList(agentdIds);
                   tt.addAll(tmp);
                   tt.add(ids);
               }
                String agentIdsStr = StringUtils.join(tt, ",");
               if(StrUtil.isNotEmpty(agentIdsStr)){
                   mediaAdvertsing.setAgentIds(agentIdsStr);
               }
            }
        }
        if (mediaAdvertsingDto.getPageSite() != null) {
            mediaAdvertsing.setPageSite(mediaAdvertsingDto.getPageSite().getValue());
        }
        try {
            if(StrUtil.isNotEmpty(mediaAdvertsingDto.getLaunchDate())){
                mediaAdvertsing.setLaunchDate(DateTime.of(mediaAdvertsingDto.getLaunchDate(),"yyyy-MM-dd HH:mm:ss"));
            }
            if(StrUtil.isNotEmpty(mediaAdvertsingDto.getStartOrderDate())){
                mediaAdvertsing.setStartOrderDate(DateTime.of(mediaAdvertsingDto.getStartOrderDate(),"yyyy-MM-dd HH:mm:ss"));
            }
            if(StrUtil.isNotEmpty(mediaAdvertsingDto.getEndOrderDate())){
                mediaAdvertsing.setEndOrderDate(DateTime.of(mediaAdvertsingDto.getEndOrderDate(),"yyyy-MM-dd HH:mm:ss"));
            }
        }catch (Exception e){
            throw new BusinessException("时间格式不正确");
        }

        if (null == mediaAdvertsingDto.getId()) {

            //新增广告时，状态设置为0
            mediaAdvertsing.setStaus(AdvertsingEunm.STATUS1.getValue());
            //新增广告时，设置为未开放
            save(mediaAdvertsing);
            if(mediaAdvertsing.getPlatform() != null){//更改媒体是否被使用状态
                mediaPlatformService.update(new UpdateWrapper<MediaPlatform>()
                        .eq("id",mediaAdvertsing.getPlatform())
                        .set("used_status", WhetherEnum.YES.getValue()));
            }
        } else {

            mediaAdvertsing.setUpdatedTime(new Date());
            updateById(mediaAdvertsing);

            //TODO 此处为修改预约记录为投放状态专用 约定businessId值不为空时将记录修改为投放状态  逻辑已修改此处暂时废弃
            /*if(mediaAdvertsingDto.getBusinessId() != null){
                mediaOrderdRecordMapper.changeRecordStatus(mediaAdvertsingDto.getBusinessId(), AppointmentEunm.STATUS9.getValue());
            }*/
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeStaus(Long id, int value) {
        baseMapper.changeStaus(id, value);
        //若是撤销状态则将所有预约记录变更为已失败
        if(AdvertsingEunm.STATUS4.getValue().equals(value)){
            SysAuth auth = AuthUtil.getSysExt();
            mediaOrderdRecordService.updateFaildStatusBatch(id,auth.getUid());
        }
    }

    @Override
    public IPage<FrontMediaAdvertsingVo> selectFrontOfPage(Page page, FrontMediaAdvertSingQuery frontMediaAdvertSingQuery, Long uid) {
        if(uid==null){
            return baseMapper.selectFrontOfPage(page, frontMediaAdvertSingQuery, null);
        }
        return baseMapper.selectFrontOfPage(page, frontMediaAdvertSingQuery, String.valueOf(uid));
    }

    @Override
    public FrontMediaAdvertsingDetilVo selectFrontDetil(Long id) {
        FrontMediaAdvertsingDetilVo vo =  baseMapper.selectFrontDetil(id);
        Long retentionTime = 0L;
        if(vo.getStartOrderDate() != null && vo.getEndOrderDate() != null){
            retentionTime = DateUtil.between(vo.getStartOrderDate(),vo.getEndOrderDate(), DateUnit.DAY);
        }
        vo.setRetentionTime(retentionTime);
        return vo;
    }

}
